package com.lihongrui.cate.controller;

/**
 * @author lihongrui
 * @create 2022-12-08 22:56
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lihongrui.cate.common.R;
import com.lihongrui.cate.entity.Category;
import com.lihongrui.cate.entity.Dish;
import com.lihongrui.cate.entity.DishFlavor;
import com.lihongrui.cate.service.CategoryService;
import com.lihongrui.cate.service.DishFlavorService;
import com.lihongrui.cate.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.lihongrui.cate.entity.dto.DishDTO;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDTO dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);
        //清理所有菜品的缓存数据
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key); //删除这些key
        return R.success("新增菜品成功");
    }

    /*
    菜品分页查询
    * */
    @GetMapping("/page")
    public R<Page<DishDTO>> page(@RequestParam("page") int page,@RequestParam("pageSize") int pageSize,@RequestParam(value = "name",required = false) String name){
        Page<Dish> page1 = new Page<>(page,pageSize);
        Page<DishDTO> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> wrapper = Wrappers.<Dish>lambdaQuery().like(name != null && name != "", Dish::getName, name);
        //添加排序条件
        wrapper.orderByDesc(Dish::getUpdateTime);

        page1 = dishService.page(page1, wrapper);
        //对象拷贝
        BeanUtils.copyProperties(page1,dishDtoPage,"records");
        List<Dish> records = page1.getRecords();
        List<DishDTO> list = records.stream().map((item) -> {
            DishDTO dishDto = new DishDTO();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /*
    修改菜单数据回显
    * */
    @GetMapping("/{id}")
    public R<DishDTO> getDishInfo(@PathVariable("id") Long id){
        DishDTO dto = new DishDTO();
        Dish dish = dishService.getById(id);
        BeanUtils.copyProperties(dish,dto);
        Category category = categoryService.getById(dish.getCategoryId());
        if(!StringUtils.isEmpty(category.getName())){
        dto.setCategoryName(category.getName());
        }
        LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = Wrappers.<DishFlavor>lambdaQuery().eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(flavorLambdaQueryWrapper);
        dto.setFlavors(list);
        return R.success(dto);
    }

    @PutMapping
    public R updateDish(@RequestBody DishDTO dto){
        log.info(dto.toString());
        dishService.updateWithFlavor(dto);
        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("修改菜品成功!");
    }

    @PostMapping("/status/{status}")
    public R updateStatus(@RequestParam("ids") String ids,@PathVariable int status){
        String[] split = ids.split(",|，");
        dishService.updateByIds(split,status);
        return R.success("操作成功!");
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDTO>> list(Dish dish){
        List<DishDTO> dishDtoList = null;
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDTO>) redisTemplate.opsForValue().get(key);
        if(dishDtoList != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);
        List<DishDTO> collect = list.stream().map(s -> {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(s, dishDTO);
            List<DishFlavor> list1 = dishFlavorService.list(Wrappers.<DishFlavor>lambdaQuery().eq(DishFlavor::getDishId, s.getId()));
            dishDTO.setFlavors(list1);
            Category category = categoryService.getById(s.getCategoryId());
            if (category!=null){
                String categoryName = category.getName();
                dishDTO.setCategoryName(categoryName);
            }
            return dishDTO;
        }).collect(Collectors.toList());
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(collect);
    }
}
